﻿using Prism.Commands;
using System.Windows;
using System.Windows.Controls;

namespace Loaf.自定义控件.Controls
{
    public class Navigation : StackPanel
    {

        /// <summary>
        /// 上一次点击的子项
        /// </summary>
        private NavigationItem LastItem { get; set; }



        /// <summary>
        /// 增加/删除  子项事件
        /// </summary>
        /// <param name="visualAdded"></param>
        /// <param name="visualRemoved"></param>
        /// <exception cref="Exception"></exception>
        protected override void OnVisualChildrenChanged(DependencyObject visualAdded, DependencyObject visualRemoved)
        {
            if (visualAdded != null)
            {
                var item = visualAdded as NavigationItem;
                if (item == null)
                    throw new Exception("子项只能是NavigationItem");

                item.Selected = new DelegateCommand<NavigationItem>(ClickItem);
            }

            base.OnVisualChildrenChanged(visualAdded, visualRemoved);
        }

        /// <summary>
        /// 子项点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ClickItem(NavigationItem sender)
        {
            if (LastItem != null)
                LastItem.IsSelected = false;

            if (sender != null)
                sender.Command.Execute(sender.CommandParameter);

            sender.IsSelected = true;
            LastItem = sender;
        }

    }
}
